package com.example.scanlogin;

import com.example.scanlogin.redis.RedisUtils;
import jakarta.validation.constraints.NotEmpty;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Objects;

/**
 * @description: 二维码扫码登录
 * @author: Leon
 * @date: 2025/1/22  14:42
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/login")
public class CodeLoginController {

    private final RedisUtils redisUtils;

    /**
     * 获取登录二维码
     */
    @GetMapping("/getLoginCode/{t}")
    //@IgnoreInterceptor(dataPermission = true, tenant = true)
    public HashMap<String, String> getAll(@PathVariable("t") @NotEmpty String t) {
        //校验token时间是否超过5秒
        //根据秒数生成临时token
        String token = SHA512Util.generateSHA512Hash(t);
        Integer status = (Integer) redisUtils.get(RedisKeyPrefix.CODE_LOGIN_PREFIX + ":" + token);
        if (Objects.equals(CodeLogin.NOT_SCANNED.getCode(), status)) {
            //直接返回Base64

        }
        //存到redis
        redisUtils.set(RedisKeyPrefix.CODE_LOGIN_PREFIX + ":" + token, CodeLogin.NOT_SCANNED.getCode(), 5);
        //返回token和携带token的图片base64
        HashMap<String, String> res = new HashMap<>();
        res.put("token", token);
        res.put("codeBase64", TextPictureConverse.generateQRCodeBase64(token, 300, 300));
        return res;
    }

    @PostMapping("/confirm")
    public void confirmLogin(@RequestParam String token) {
        //当前登录人Id
        Long currentUserId = ContextUtil.getCurrentUserId();
        //判断token存在，userId正确
        Integer status = (Integer) redisUtils.get(RedisKeyPrefix.CODE_LOGIN_PREFIX + ":" + token);
        if (!Objects.isNull(status)) {
            if (Objects.equals(CodeLogin.NOT_SCANNED.getCode(), status)) {
                //删除
                redisUtils.del(RedisKeyPrefix.CODE_LOGIN_PREFIX + ":" + token);
                //设置新的redis进行登录携带userId
                redisUtils.set(RedisKeyPrefix.CODE_LOGIN_PREFIX + ":" + token, CodeLogin.SUCCESS.getCode() + "-" + currentUserId, 5);
            }
        }
    }


    // 检查登录状态
    @GetMapping("/status")
    //@IgnoreInterceptor(dataPermission = true, tenant = true)
    @Transactional(rollbackFor = Exception.class)
    public String checkLoginStatus(@RequestParam String token) {
        //查询redis状态
        String redisRes = (String) redisUtils.get(RedisKeyPrefix.CODE_LOGIN_PREFIX + ":" + token);
        String[] split = redisRes.split("-");
        String status = split[0];
        String userId = split[1];
        if (!Objects.isNull(status)) {
            if (Objects.equals(CodeLogin.SUCCESS.getCode(), Integer.parseInt(status))) {
                //根据userId获取登录token，走正常的登录逻辑返回给PC
              	//清除缓存
                redisUtils.del(RedisKeyPrefix.CODE_LOGIN_PREFIX + ":" + token);
                return token;
            }
        }
        return null;
    }
}


